package com.kalaqia.base.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.os.MessageQueue;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewStub;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;


/**
 * @author kalaqia 421407393@qq.com
 * @since 0.0.4
 */
public abstract class BaseActivity extends AppCompatActivity implements BGASwipeBackHelper.Delegate {

    protected BGASwipeBackHelper mSwipeBackHelper;
    protected TitleToolbar mToolbar;
    private ActivityFunction annotation;
    private boolean swipeBackAble;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        if (getClass().isAnnotationPresent(ActivityFunction.class)) {
            annotation = getClass().getAnnotation(ActivityFunction.class);
        }

        if (annotation != null && annotation.swipeBackAble()) {
            swipeBackAble = true;
            initSwipeBackFinish();
        }

        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());

        initView(savedInstanceState);

        Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                onInitCreate();
                return false;
            }
        });
    }

    protected void initSwipeBackFinish() {
        mSwipeBackHelper = new BGASwipeBackHelper(this, this);
        mSwipeBackHelper.setSwipeBackEnable(true);
        mSwipeBackHelper.setIsOnlyTrackingLeftEdge(false);
        mSwipeBackHelper.setIsWeChatStyle(true);
        mSwipeBackHelper.setShadowResId(R.drawable.bga_sbl_shadow);
        mSwipeBackHelper.setIsNeedShowShadow(true);
        mSwipeBackHelper.setIsShadowAlphaGradient(true);
        mSwipeBackHelper.setSwipeBackThreshold(0.3f);
        mSwipeBackHelper.setIsNavigationBarOverlap(false);
    }

    protected void onInitCreate() {

    }

    protected int getLayoutId() {
        return R.layout.fragment_base;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                hideSoftInput(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private boolean isShouldHideInput(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }

    private void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (im == null) {
                return;
            }
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    protected void initView(Bundle savedInstanceState) {

        View customView;

        if (annotation != null && TitleToolbar.SCENE_HIDDEN != annotation.toolbarScene()) {
            setContentView(R.layout.activity_base);
            ViewStub titleStub = findViewById(R.id.id_base_toolbar_stub);
            mToolbar = (TitleToolbar) titleStub.inflate();
            mToolbar.initTitleScene(annotation.toolbarScene());
            ViewCompat.setElevation(mToolbar, 2F);
            mToolbar.setFitsSystemWindows(true);
            setSupportActionBar(mToolbar);

            ActionBar actionBar = getSupportActionBar();
            if (annotation.titleRes() != 0 && actionBar != null) {
                actionBar.setDisplayShowTitleEnabled(false);
                mToolbar.setTitle(annotation.titleRes());
            }

            if (swipeBackAble) {
                mToolbar.setDisplayShowHomeEnabled(true);
                mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onBackPressed();
                    }
                });
            }

            ViewStub viewStub = findViewById(R.id.id_base_content_stub);
            viewStub.setLayoutResource(getLayoutId());
            viewStub.inflate();
        } else {
            customView = LayoutInflater.from(this).inflate(getLayoutId(), null);
            setContentView(customView);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions
            , @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean isSupportSwipeBack() {
        return swipeBackAble;
    }

    @Override
    public void onSwipeBackLayoutSlide(float slideOffset) {

    }

    @Override
    public void onSwipeBackLayoutCancel() {

    }

    @Override
    public void onSwipeBackLayoutExecuted() {
        mSwipeBackHelper.swipeBackward();
    }

    @Override
    public void onBackPressed() {
        if (mSwipeBackHelper.isSliding()) {
            return;
        }
        mSwipeBackHelper.backward();
    }

}
